import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
import { randomString } from 'src/utils';
import {
  BeforeInsert,
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
} from 'typeorm';
import * as bcrypt from 'bcryptjs';
import RandomNickname from '@sugarfish/random-nickname';
import { Exclude } from 'class-transformer';

const res = new RandomNickname();

@Entity('user')
export class UserEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @CreateDateColumn({
    name: 'created_at',
    comment: '创建时间',
  })
  created_at: Date;

  @Column({
    charset: 'utf8mb4',
    length: 255,
    default: `${res.getRandomName()}${randomString(6)}`,
    comment: '昵称',
  })
  @IsString()
  nickname: string;

  @Column({
    default: 'https://static.turbineindustry.com/default/images/avatar.jpg',
    comment: '头像',
  })
  avatar: string;

  @Exclude()
  @Column({
    default: '1',
    comment: '性别',
  })
  @IsString()
  sex: string;

  @Column({ default: null, comment: '微信用户openid' })
  openid: string;

  @Exclude()
  @Column('simple-enum', { enum: ['root', 'author', 'visitor'] })
  role: string; // 用户角色

  @Column({
    type: 'varchar',
    comment: '地址',
    nullable: true, // 可以不传
    default: null,
  })
  address: string;

  @Column({
    type: 'varchar',
    comment: '简介',
    nullable: true, // 可以不传
    default: '这个人很懒，什么都没留下',
  })
  introduce: string;

  @Exclude()
  @Column({ length: 60, comment: '密码', default: '' })
  @IsString()
  @IsNotEmpty()
  password: string;

  @Column({ length: 11, comment: '用户名', default: null })
  @IsString()
  @IsNotEmpty()
  username: string;

  @Exclude()
  @Column({
    type: 'int',
    nullable: true, // 可以不传
    default: 0,
    name: 'is_delete',
    comment: '0: 否, 1: 是',
  })
  @IsNumber()
  is_delete: number;

  @BeforeInsert()
  async encryptPwd() {
    if (!this.password) return;
    this.password = bcrypt.hashSync(this.password, 10);
  }
}
